package server

import (
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/jmoiron/sqlx"
	"os"
	"time"
)

//定时任务
func RunCronTask(db *sqlx.DB) {
	ticker1 := time.NewTicker(6 * time.Hour)

	testTask(db)
	for {
		select {
		case <-ticker1.C:
			go deleteExpiredSession(db)
		}
	}
}

//删除过期session
func deleteExpiredSession(db *sqlx.DB) {
	expire_limit := GetBeginningOfToday().Add(-time.Hour * 24 * SessionExpiredDays).Format("2006-01-02")
	_, err := db.Exec("delete from tb_session where create_date < ?", expire_limit)
	if err != nil {
		fmt.Println("delete tb_session failed!!")
	}
}

func testSts() {
	//构建一个阿里云客户端, 用于发起请求。
	//构建阿里云客户端时，需要设置AccessKey ID和AccessKey Secret。
	client, err := sts.NewClientWithAccessKey("cn-beijing", "LTAI4GCwxryKpybrKQm9XtkR", "dGW92uGXPvgFunJH9qY9dbREOmRH4P")

	//构建请求对象。
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = "https"

	//设置参数。
	request.RoleArn = "acs:ram::1310537980091361:role/ramosstest"
	request.RoleSessionName = "user123456789"
	request.DurationSeconds = "3600"

	//发起请求，并得到响应。
	response, err := client.AssumeRole(request)
	if err != nil {
		fmt.Print(err.Error())
	}
	fmt.Printf("response is %#v\n", response)
}

func testTask(db *sqlx.DB) {

}

func HandleError(err error) {
	fmt.Println("Error:", err)
	os.Exit(-1)
}

func testUrl() {
	client, err := oss.New("oss-cn-beijing.aliyuncs.com", "LTAI4FxzvtcmFNzMsWzuQG8U", "z23DiSo40RhVqnALOZ72wHgC9D4o4l")
	if err != nil {
		HandleError(err)
	}

	bucketName := "wangjun-test-bucket"
	objectName := "test/aaa.jpg"
	//localFilename := "<yourLocalFilename>"

	// 获取存储空间。
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}

	// 签名直传。
	signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 600)
	if err != nil {
		HandleError(err)
	} else {
		fmt.Println("----", signedURL)
	}
}
